<script setup>
import { ref } from 'vue';
import { upload_excel } from '../server/upload_excel';

import * as XLSX from 'xlsx';

const fileList = ref([]);           // 导入的文件列表
let uploadFile_status = ref('');    // 上传文件的状态

// 图标的映射
let iconList = {
    doc: '/word.jpg',
    ppt: '/ppt.jpg',
    excel: '/excel.jpg',
};

const fileDom = document.createElement('input');
fileDom.type = 'file';
fileDom.setAttribute('accept', '.xlsx, .xls');

// 监听文件选择事件
fileDom.addEventListener('change', (event) => {
    // 获取用户选择的文件列表
    const files = event.target.files;
    // 清空之前的显示内容
    let newFileList = [];
    // 遍历文件列表并显示文件信息
    for (let i = 0; i < files.length; i++) {
        let tmp = {
            id: files[i].name,
            name: files[i].name
        };
        newFileList.push(tmp);
    }
    fileList.value = newFileList;
});

// 上传按钮的点击事件
function inputFile() {
    fileDom.click();
}

function uploadFile() {
    uploadFile_status.value = "正在检查是否有文件.....";
    let file = fileDom.files[0];
    let fileName = file.name;
    if (!file) {
        alert('请选择文件');
        return ;
    }
    uploadFile_status.value = "加载该文件中.......";
    // 读取文件完成后执行的回调函数
    const reader = new FileReader();
    reader.onload = async (e) => {
        const data = e.target?.result;
        if (data) {
            const workbook = XLSX.read(data, { type: 'array' });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];

            // 将工作表转换为 JSON
            const json = XLSX.utils.sheet_to_json(worksheet);
            console.log('【解析excel表格的数据】', json);

            // 转换为后端可以接受的数据
            let lastId = null;
            let nowObj = {};
            let newJson = [];
            for (let i = 0; i < json.length; i++) {
                if (lastId != json[i]['序号']) {
                    if (Object.keys(nowObj).length != 0) {
                        newJson.push(nowObj);
                    }
                    lastId = json[i]['序号'];
                    nowObj = {
                        序号: json[i]['序号'],
                        实施机构: json[i]['实施机构'],
                        事项类别: json[i]['事项类别'],
                        事项名称: json[i]['事项名称'],
                        设定依据: json[i]['设定依据'],
                        二级事项: [
                            {
                                二级序号: json[i]['二级序号'],
                                二级事项名称: json[i]['二级事项名称'],
                                部门: json[i]['部门']
                            }
                        ]
                    };
                } else {
                    nowObj['二级事项'].push({
                        二级序号: json[i]['二级序号'],
                        二级事项名称: json[i]['二级事项名称'],
                        部门: json[i]['部门']
                    });
                }
            }
            if (Object.keys(nowObj).length != 0) {
                newJson.push(nowObj);
            }

            console.log('【后端可以接受的数据】', newJson);

            uploadFile_status.value = "上传中.......";
            // 发送给后端
            upload_excel.uploadExcel(fileName, newJson).then((res) => {
                uploadFile_status.value = "上传成功 ! ! ! ! !";
            }).catch((err) => {
                console.log(err);
                uploadFile_status.value = "上传失败 ! ! ! ! !";
            });
        }
    };

    // 开始读取文件
    reader.readAsArrayBuffer(file);
}

</script>

<template>
<div class="page">
    <div class="top-line">
        <div class="btn" @click="inputFile">上传文件</div>
    </div>
    <div class="loadFileBox" v-if="fileList.length">
        <div class="loadFileList">
            <div class="file-item" v-for="item in fileList" style="--icon: url(/excel.jpg)" :key="item.id">{{ item.name }}</div>
        </div>
        <div class="bottom-line">
            <div class="btn uploadBtn" @click="uploadFile" :text="uploadFile_status">确认上传</div>
        </div>
    </div>
</div>
</template>

<style scoped>
.page {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    padding: 10px;
}
.top-line {
    padding: 20px;
}
.btn {
    width: 100px;
    height: auto;
    background-color: rgb(30, 111, 255);
    color: #fff;
    border-radius: 10px;
    padding: 10px;
    text-align: center;
    margin-top: 20px;
}
.btn:hover {
    background-color: rgb(30, 98, 216);
}
.uploadBtn {
    position: relative;
}
.uploadBtn::after {
    color: #000;
    content: attr(text);
    display: block;
    position: absolute;
    top: 50%;
    right: -30px;
    transform: translate(100%, -50%);
}
.loadFileBox {
    width: 80%;
    padding: 20px;
}
.loadFileList {
    padding: 10px;
}
.file-item {
    padding: 10px;
    padding-left: 70px;
    position: relative;
}
.file-item::before {
    --size: 30px;
    content: "";
    display: block;
    width: var(--size);
    height: var(--size);
    background-image: var(--icon);
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
    position: absolute;
    top: 50%;
    left: 35px;
    transform: translateY(-50%);
}
.file-item:hover {
    border-radius: 10px;
    background-color: rgb(236, 236, 236);
}
</style>